package com.aidansmeaton.weightmanager;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.aidansmeaton.weightmanager.adapter.DiaryFoodAdapter;
import com.aidansmeaton.weightmanager.data.DatabaseHelper;
import com.aidansmeaton.weightmanager.util.ImageHelper;
import com.aidansmeaton.weightmanager.util.TimeFormatter;

/** The first activity in the app. */
public class DiaryFoodFavouritesActivity extends ListActivity {
	
	private DatabaseHelper db;
	private Cursor c;
	
	private String date;
	private List<Integer> selected;
	
	private Button addButton;
	
	ListAdapter a;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_food_favourites);
        
        // This activity has the theme of a dialog, and will be displayed as such
        setTitle(getString(R.string.diary_food_favourites_header));
        
        db = DatabaseHelper.getInstance(this);
        date = getIntent().getStringExtra("Date");
        selected = new ArrayList<Integer>();
        
        addButton = (Button) findViewById(R.id.add);
        
        c = db.getFoodLogs();
        Log.w("FOOD LOGS",""+c.getCount());
        
        setListAdapter(new DiaryFoodAdapter(this, c));
        
        getListView().setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	
            	Integer tag = (Integer) view.getTag(R.id.food_row);
            	if (selected.contains(tag)){
            		selected.remove(tag);
            		view.setBackgroundColor(0);
            	}
            	else {
            		selected.add(tag);
            		view.setBackgroundColor(R.color.grey3);
            	}
            	addButton.setClickable(!selected.isEmpty());
            	addButton.setEnabled(!selected.isEmpty()); 
            }
		});
        
        // stop soft keyboard popping up automatically
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        
	}
    
    
    public void addClick(View v){
    	
    	if (selected.isEmpty()) Toast.makeText(this, "Select foods to add.", Toast.LENGTH_SHORT).show();
    	else {
	    	for (Integer original_food_log_id : selected){
	    		Cursor c = db.getFoodLog(original_food_log_id);
	        	c.moveToFirst();
	        	
	        	String name = c.getString(DatabaseHelper.FOOD_LOG_NAME);
	        	String note = c.getString(DatabaseHelper.FOOD_LOG_NOTE);
	        	String photoPath = c.getString(DatabaseHelper.FOOD_LOG_PHOTO);
	        	
	        	ContentValues cv = new ContentValues();
	        	cv.putNull("_id");
	        	cv.put("date", date);
	        	cv.putNull("meal");
	        	if (name != null) cv.put("name", name); else cv.putNull("name");
	        	cv.putNull("measurement");
	        	cv.putNull("quantity");
	        	if (note != null) cv.put("note", note); else cv.putNull("note");
	        	if (photoPath != null) cv.put("photo", photoPath); else cv.putNull("photo");
	        	
	        	int new_food_log_id = (int) db.addFoodLog(cv);
	        	
	        	Cursor c2 = db.getPlateLogs(original_food_log_id);
	        	c2.moveToFirst();
	        	while (!c2.isAfterLast()){
	        		ContentValues cv2 = new ContentValues();
	        		cv2.putNull("_id");
	        		cv2.put("food_log_id",new_food_log_id);
	        		cv2.put("grade",c2.getInt(DatabaseHelper.PLATE_LOG_GRADE));
	        		cv2.put("note",c2.getString(DatabaseHelper.PLATE_LOG_NOTE));
	        		cv2.put("calories",c2.getInt(DatabaseHelper.PLATE_LOG_CALORIES));
	        		db.addPlateLog(cv2);
	        		c2.moveToNext();
	        	}	
	    	}
	    	finish();
    	}
    }
    
    public void cancelClick(View v){
    	finish();
    }

	private void refreshListView(){
    	c.requery();
    	((FoodFavouritesAdapter)getListView().getAdapter()).changeCursor(c);
    }
    
    private class FoodFavouritesAdapter extends CursorAdapter {
		private LayoutInflater inflater;
		
		public FoodFavouritesAdapter(Context context, Cursor cursor) {
			super(context, cursor);
			
			inflater = LayoutInflater.from(context);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			
			// Set ID tag
			view.setTag(cursor.getInt(DatabaseHelper.MOOD_LOG_ID));
						
			TextView comment = (TextView) view.findViewById(R.id.mood_comment);
			comment.setText(cursor.getString(DatabaseHelper.MOOD_LOG_COMMENT));
			
			TextView time = (TextView) view.findViewById(R.id.mood_time);
			time.setText(TimeFormatter.getTimeAsString(cursor.getString(DatabaseHelper.MOOD_LOG_DATE),false));
			
			ImageView emoticon = (ImageView) view.findViewById(R.id.mood_emoticon);
			emoticon.setImageResource(ImageHelper.getEmoticon(cursor.getInt(DatabaseHelper.MOOD_LOG_EMOTICON)));
			
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			return inflater.inflate(R.layout.diary_food_row_record, null);
		}
	}
	
}